# -*- coding: gbk -*-

import web, cjson
import hall, uigate
import codecs

Unicode = codecs.getdecoder('utf8')

def unicodeHeader (mesg, headerList):
    return map(lambda x: Unicode(x, 'replace')[0],
               mesg.getMailHeader(headerList))

def safeUnicode (str):
    try:
        return Unicode(str, 'replace')
    except:
        return ''


class UIContent:
    GET  = web.autodelegate('GET_')

    def GET_mail (self, docID):
        docID = int(docID[1:])

        mesg = uigate.MessageView(docID)

        header = unicodeHeader(mesg, ('SUBJECT', 'FROM', 'TO', 'CC',
                                      'DATE', 'MESSAGE-ID'))

        # Select content payload
        selected = -1
        for i in range(0, len(mesg.payloadHeader)):
            if (mesg.payloadHeader[i][1][: 10] == 'text/plain' or
                mesg.payloadHeader[i][1][: ] == 'message/rfc822'):
                selected = i
                break
        if (selected == -1):
            content = 'No content'
        else:
            data = mesg.getPayload(selected)
            try:
                content = Unicode(data, 'replace')[0]
            except:
                content = ''

        ret = {
            'subject' : header[0],
            'from' : header[1], 'to' : header[2], 'cc' : header[3],
            'date' : header[4],
            'messageid' : header[5],
            'tags' : mesg.tags,            
            'content' : content,
            'payload' : map(lambda x: (Unicode(x[0], 'replace')[0], x[1]),
                            mesg.payloadHeader)
            }

        web.header('Content-Type', 'text/javascript')
        print cjson.encode((ret,))

    def GET_payload (self, path):
        tmp, docID, payloadName = path.split('/')
        docID = int(docID)

        mesg = uigate.MessageView(docID)
        found = False
        for payloadNum in range(0, len(mesg.payloadHeader)):
            if (mesg.payloadHeader[payloadNum][0] == payloadName):
                found = True
                break

        if (not found):
            return web.notfound();
                
        header = mesg.payloadHeader[payloadNum]

        web.header('Content-Type', header[1])
        print mesg.getPayload(payloadNum)        
    
